package com.tennis.tennisreservation.service.impl;

import com.tennis.tennisreservation.entity.Coupon;
import com.tennis.tennisreservation.repository.CouponRepository;
import com.tennis.tennisreservation.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 红包服务实现类
 */
@Service
public class CouponServiceImpl implements CouponService {
    
    private static final Logger logger = LoggerFactory.getLogger(CouponServiceImpl.class);
    
    @Autowired
    private CouponRepository couponRepository;
    
    @Override
    @Transactional
    public Coupon createCoupon(Coupon coupon) {
        logger.info("进入createCoupon方法，有效期: 从 {} 到 {}", coupon.getValidFrom(), coupon.getValidTo());
        
        // 设置创建时间，如果是新建的话
        if (coupon.getCreateTime() == null) {
            coupon.setCreateTime(LocalDateTime.now());
        }
        
        // 设置默认状态
        if (!StringUtils.hasText(coupon.getStatus())) {
            coupon.setStatus("未使用");
        }
        
        Coupon saved = couponRepository.save(coupon);
        logger.info("保存后的红包，有效期: 从 {} 到 {}", saved.getValidFrom(), saved.getValidTo());
        return saved;
    }
    
    @Override
    @Transactional
    public List<Coupon> createCouponBatch(Long userId, BigDecimal amount, int validDays, int count) {
        List<Coupon> coupons = new ArrayList<>();
        
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime validTo = now.plusDays(validDays);
        
        for (int i = 0; i < count; i++) {
            Coupon coupon = new Coupon();
            coupon.setUserId(userId);
            coupon.setAmount(amount);
            coupon.setStatus("未使用");
            coupon.setValidFrom(now);
            coupon.setValidTo(validTo);
            coupon.setCreateTime(now);
            
            coupons.add(coupon);
        }
        
        return couponRepository.saveAll(coupons);
    }
    
    @Override
    public Coupon getCouponById(Long id) {
        return couponRepository.findById(id).orElse(null);
    }
    
    @Override
    public List<Coupon> getCouponsByUserId(Long userId) {
        return couponRepository.findByUserId(userId);
    }
    
    @Override
    public Map<String, Object> getCouponList(int page, int size, Long userId, String status) {
        Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC, "createTime"));
        
        Page<Coupon> pageResult;
        
        if (userId != null && StringUtils.hasText(status)) {
            // 根据用户ID和状态查询
            List<Coupon> coupons = couponRepository.findByUserIdAndStatus(userId, status);
            // 简单处理，非真实分页
            int start = (page - 1) * size;
            int end = Math.min(start + size, coupons.size());
            List<Coupon> pagedCoupons = start < end ? coupons.subList(start, end) : new ArrayList<>();
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", pagedCoupons);
            result.put("total", coupons.size());
            return result;
        } else if (userId != null) {
            // 根据用户ID查询
            pageResult = couponRepository.findByUserId(userId, pageable);
        } else if (StringUtils.hasText(status)) {
            // 根据状态查询
            List<Coupon> coupons = couponRepository.findByStatus(status);
            // 简单处理，非真实分页
            int start = (page - 1) * size;
            int end = Math.min(start + size, coupons.size());
            List<Coupon> pagedCoupons = start < end ? coupons.subList(start, end) : new ArrayList<>();
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", pagedCoupons);
            result.put("total", coupons.size());
            return result;
        } else {
            // 查询全部
            pageResult = couponRepository.findAll(pageable);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getContent());
        result.put("total", pageResult.getTotalElements());
        
        return result;
    }
    
    @Override
    @Transactional
    public Coupon useCoupon(Long id) {
        Optional<Coupon> optionalCoupon = couponRepository.findById(id);
        if (optionalCoupon.isPresent()) {
            Coupon coupon = optionalCoupon.get();
            
            // 检查红包是否可用
            if (!"未使用".equals(coupon.getStatus())) {
                throw new RuntimeException("红包状态不可用");
            }
            
            LocalDateTime now = LocalDateTime.now();
            
            // 检查是否在有效期内
            if (coupon.getValidFrom().isAfter(now) || coupon.getValidTo().isBefore(now)) {
                throw new RuntimeException("红包不在有效期内");
            }
            
            // 设置为已使用
            coupon.setStatus("已使用");
            coupon.setUseTime(now);
            
            return couponRepository.save(coupon);
        }
        
        throw new RuntimeException("红包不存在");
    }
    
    @Override
    @Transactional
    public boolean cancelCoupon(Long id) {
        Optional<Coupon> optionalCoupon = couponRepository.findById(id);
        if (optionalCoupon.isPresent()) {
            Coupon coupon = optionalCoupon.get();
            
            // 只有未使用的红包可以取消
            if (!"未使用".equals(coupon.getStatus())) {
                return false;
            }
            
            // 设置为已作废
            coupon.setStatus("已作废");
            couponRepository.save(coupon);
            
            return true;
        }
        
        return false;
    }
    
    @Override
    @Transactional
    public int checkAndUpdateExpiredCoupons() {
        LocalDateTime now = LocalDateTime.now();
        List<Coupon> expiredCoupons = couponRepository.findExpiredCoupons(now);
        
        if (expiredCoupons.isEmpty()) {
            return 0;
        }
        
        // 将所有过期红包标记为已过期
        for (Coupon coupon : expiredCoupons) {
            coupon.setStatus("已过期");
        }
        
        couponRepository.saveAll(expiredCoupons);
        
        return expiredCoupons.size();
    }
    
    @Override
    public List<Coupon> getValidCoupons(Long userId) {
        LocalDateTime now = LocalDateTime.now();
        return couponRepository.findValidCoupons(userId, now);
    }
} 